package com.gopay.scheduler.job;

import com.gopay.common.constants.trans.PgStatus;
import com.gopay.common.constants.trans.Trans00700AssistStatus;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.remote.order.MainOrderField;
import com.gopay.remote.order.MainOrderUpdateRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by zhaojt on 2017/10/12.
 *
 * 更新异步式网关单笔付款到银行订单状态
 */
public class ModifyGateway00700StateJob extends GopayBaseJob {

    private Logger logger = LoggerFactory.getLogger(GopayBaseJob.class);

    private static final int QUERYCOUNT = 300;

    private long timeSpan = 3 * 60 * 1000; //修改多久以前的订单  毫秒

    @Resource(name = "cpsGeneralMainOrderOperClient")
    private MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient;

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;


    @Resource(name = "cpsGeneralMainOrderDAO")
    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO;


    @Override
    protected void doJobInternal() {
        long startMillions = System.currentTimeMillis();
        logger.info("更新异步式网关单笔付款到银行订单状态 处理开始 ");

        long time = startMillions - timeSpan;
        List<Object[]> list = new ArrayList<>();
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("   select a.gopay_order_id, o.trans_dtl_sq  ");
            sb.append("     from CPS_TRANS_00700_ASSIST a  ");
            sb.append("     left join cps_gen_main_order o  ");
            sb.append("       on o.gopay_order_id = a.gopay_order_id  ");
            sb.append("     left join PG_GEN_ORDER_STATUS_DTL os  ");
            sb.append("       on os.id = o.trans_dtl_sq  ");
            sb.append("    where a.status = '" + Trans00700AssistStatus.INIT.value + "'  ");
            sb.append("      and a.created_ts > sysdate - 1  ");
            sb.append("      and a.created_ts <= :time  ");
            sb.append("      and os.status = '" + PgStatus.FAIL.value + "'  ");
            sb.append("      and o.txn_sta_cd = 30000 ");  //订单状态为30000
            sb.append("      and o.accounting_point is null  ");  //记账点为空
            sb.append("    order by a.created_ts asc  ");

            Map<String, Object> map = new HashMap();
            map.put("time", new Date(time));

            list = commonQueryDAO.findBySql(sb.toString(), map, 1, QUERYCOUNT);

            callCps(list);

        }catch (Exception e){
            logger.error("更新异步式网关单笔付款到银行订单状态 异常 ：", e);
        }

        long endMiilions = System.currentTimeMillis();
        long result = (endMiilions - startMillions);
        logger.info("更新异步式网关单笔付款到银行订单状态 处理结束 数量{},耗费{}毫秒", list.size(), result);
    }

    private void callCps(List<Object[]> assists) {

        if (!(assists.isEmpty())) {
            logger.info("取到待处理数据条数：" + assists.size());

            logger.info("开始调用");
            for (Object[] order : assists) {
                String orderId = String.valueOf(order[0]);
                String dtlId = String.valueOf(order[1]);


                logger.info("准备更新订单状态 orderId = " + orderId);
                CpsGenMainOrder mainOrder = cpsGeneralMainOrderDAO.findByGopayOrderId(orderId);

                if(mainOrder == null){
                    return;
                }

                if(TxnStaCode.TXN_STA_CD_30000.value != mainOrder.getTxnStaCd()){
                    logger.info("订单状态不是 30000  continue !");
                    continue;
                }

                try {
                    Map<MainOrderField, String> map = new HashMap<>();
                    Date date = new Date();
                    map.put(MainOrderField.TXN_STA_CD, TxnStaCode.TXN_STA_CD_20001.value + "");
                    map.put(MainOrderField.TRAN_FINISH_TIME, DateUtils.format(date));
                    map.put(MainOrderField.LAST_UPDATE_TIME, DateUtils.format(date));

                    cpsGeneralMainOrderOperClient.updateMany(orderId, map);

                } catch (Exception e) {
                    logger.error("更新单条订单异常：", e);
                }
            }

        } else {
            logger.info("00700 取回列表为空...");
        }
    }

}
